// 物料组库
import React, {Component} from 'react';
import {connect} from 'react-redux';
import actions_material from '../../store/actions/materialGroup';
import specs_library from '../../store/actions/specsLibrary';
import {Tree} from 'antd';

import '../materialGroup/MaterialGroup.scss';

const {TreeNode} = Tree;

class SpecsLibraryLeft extends Component {

  // 点击选择
  onSelect = async (selectedKeys, info) => {
    console.log(selectedKeys, info);

    const {SPECS_SELECT, SPECS_IS_SELECT, GET_SPECSLIBRARY_INFO} = this.props;
    const code = selectedKeys.toString().split(',')[1];
    // 被选择的code
    await SPECS_SELECT(code);
    // 是否进行了选择
    await SPECS_IS_SELECT(info.selected);
    // 获取所点击的数据
    await GET_SPECSLIBRARY_INFO(code);
  };

  // 自己定义的渲染tree函数
  myRender = data => {
    return data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.cate_title} key={[item.id, item.cate_code]}>
            {this.myRender(item.children)}
          </TreeNode>
        );
      } else {
        return (<TreeNode title={item.cate_title} key={[item.id, item.cate_code]} isLeaf/>);
      }
    });
  };

  componentDidMount() {
    this.props.INIT_DATA();
  }

  render() {
    if (this.props.data) {
      const {data} = this.props;
      return (
        data ? <div className='materialBox'>
            <div className='materialBoxk'>
              <div className='treeBox'>
                <Tree
                  accordion
                  multiple={false}
                  showLine
                  blockNode
                  onSelect={this.onSelect}
                >
                  {this.myRender(data)}
                </Tree>
              </div>
            </div>
          </div>
          :
          null
      );
    }
  }
}

const mapStateToProps = state => {
  console.log(state);
  return {
    data: state.materialGroup.data
  };
};

export default connect(mapStateToProps, {...actions_material, ...specs_library})(SpecsLibraryLeft);

